﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.ComponentModel;
using System.Xml;

namespace wxtools
{
    /// <summary>
    /// Description of QQListBox.
    /// </summary>
    public partial class WxListBox : ListBox
    {
        public WxListBoxItem mouseitem;
        public string _xmlpath = "date.xml";
        private WxListBoxItemCollection _items;

        public WxListBox()
            : base()
        {
            _items = new WxListBoxItemCollection(this);
            base.DrawMode = DrawMode.OwnerDrawVariable;
            //InitializeComponent();
            this.SetStyle(ControlStyles.UserPaint, true);
            this.SetStyle(ControlStyles.DoubleBuffer, true);// 双缓冲
            this.SetStyle(ControlStyles.ResizeRedraw, true);//调整大小时重绘
            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景.
            this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);// 双缓冲
            this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            //this.BackColor=Color.Transparent;
        }

        [Localizable(true)]
        [MergableProperty(false)]
        [DesignerSerializationVisibility(
        DesignerSerializationVisibility.Content)]
        public string Xmlpath
        {
            get { return _xmlpath; }
            set { _xmlpath = value; }
        }

        public new WxListBoxItemCollection Items
        {
            get { return _items; }
        }

        internal ListBox.ObjectCollection OldItems
        {
            get { return base.Items; }
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            //Bitmap bg=new Bitmap(this.ClientRectangle.Width,this.ClientRectangle.Height);
            //Graphics g =Graphics.FromImage(bg);
            Graphics g = e.Graphics;
            #region 绘制选中项
            //判断是否有选中项
            if (this.Focused && this.SelectedItem != null)
            {
                //得到选中项的区域
                Rectangle bounds = this.GetItemRectangle(this.SelectedIndex);
                //判断选中项是否为分类
                if (Items[this.SelectedIndex].IsClass)
                {
                    //g.FillRectangle(new SolidBrush(Color.FromArgb(230,238,241)),bounds);
                    //Items[this.SelectedIndex].DrawImage(global::QQListBox.Properties.Resources.MainPanel_FolderNode_collapseTexture, new Rectangle(bounds.X+3,bounds.Y+6,12,12));
                    g.DrawString(Items[this.SelectedIndex].Title, new Font("微软雅黑", 9), new SolidBrush(Color.Black), bounds.Left + 15, bounds.Top + 4);
                }
                else
                {
                    g.FillRectangle(new SolidBrush(Color.FromArgb(252, 233, 161)), bounds);
                }

            }
            #endregion

            //循环绘制每项
            for (int i = 0; i < Items.Count; i++)
            {
                Rectangle bounds = this.GetItemRectangle(i);
                WxListBoxItem item = Items[i];
                if (item.IsClass == true)
                {
                    //g.FillRectangle(new SolidBrush(Color.FromArgb(50,230,238,241)),bounds);
                    //g.DrawImage(global::QQListBox.Properties.Resources.MainPanel_FolderNode_collapseTexture, new Rectangle(bounds.X+3,bounds.Y+6,12,12));
                    if (mouseitem == Items[i] && mouseitem != this.SelectedItem)
                    {
                        g.FillRectangle(new SolidBrush(Color.FromArgb(50, 230, 238, 241)), bounds);
                    }
                    g.DrawString(item.Title, new Font("微软雅黑", 9), new SolidBrush(Color.Black), bounds.Left + 15, bounds.Top + 4);
                }
                else
                {

                    if (item != this.SelectedItem)
                    {

                        Color backColor = Color.FromArgb(20, 216, 211, 211);
                        using (SolidBrush brush = new SolidBrush(backColor))
                        {
                            //g.FillRectangle(new SolidBrush(Color.White),bounds);
                            g.FillRectangle(brush, new Rectangle(bounds.X + 1, bounds.Y + 1, bounds.Width - 2, bounds.Height - 1));
                        }
                    }
                    if (mouseitem == Items[i] && mouseitem != this.SelectedItem)
                    {
                        Color backColor = Color.FromArgb(200, 192, 224, 248);
                        using (SolidBrush brush = new SolidBrush(backColor))
                        {
                            //g.FillRectangle(new SolidBrush(Color.White),bounds);
                            g.FillRectangle(brush, new Rectangle(bounds.X + 1, bounds.Y + 1, bounds.Width - 2, bounds.Height - 1));
                        }

                    }
                    Image image = item.Image;
                    string text = item.ToString();

                    if (image != null)
                    {
                        g.InterpolationMode = InterpolationMode.HighQualityBilinear;
                        g.DrawImage(image, new Rectangle(bounds.X + 12, bounds.Y + 7, image.Size.Width, image.Size.Height));
                    }
                    int tw = 40;
                    string temp = item.Remarks + (!string.IsNullOrEmpty(item.Title) ? "(" + item.Title + ")" : "");
                    if (!string.IsNullOrEmpty(temp))
                    {
                        g.DrawString(temp, new Font("微软雅黑", 9), new SolidBrush(this.ForeColor), bounds.Left + tw + 15, bounds.Top + 4);
                        tw = item.Remarks.Length + tw + 25;
                        // item.Remarks.
                    }
                    // GetTextSize()
                    //g.DrawString("(" + item.Title + ")", /*this.Font*/new Font("微软雅黑", 9), new SolidBrush(Color.FromArgb(128, 128, 128)), bounds.Left + tw + 15, bounds.Top + 4);
                    g.DrawString(item.Text, new Font("微软雅黑", 9), new SolidBrush(Color.FromArgb(128, 128, 128)), bounds.Left + 40 + 15, bounds.Top + 19);

                }
            }
            base.OnPaint(e);
            // e.Graphics.DrawImage(bg,this.ClientRectangle);
        }



        protected override void OnMeasureItem(MeasureItemEventArgs e)
        {
            base.OnMeasureItem(e);
            try
            {
                WxListBoxItem item = Items[e.Index];
                if (item.IsClass == true)
                { e.ItemHeight = 25; }
                else
                { e.ItemHeight = 54; }
            }
            catch { }
        }
        protected override void OnClick(EventArgs e)
        {
            base.OnClick(e);
            //this.Items.Clear();
            //while ( this.SelectedItems.Count > 0 )
            //this.Items.Remove ( this.SelectedItems[0] );
        }
        protected override void OnSelectedIndexChanged(EventArgs e)
        {
            base.OnSelectedIndexChanged(e);
            WxListBoxItem item = Items[this.SelectedIndex];
            //MessageBox.Show(this.SelectedIndex.ToString());
            if (item.IsClass == true && item.IsExpand == true)
            {
                for (int i = this._items.Count - 1; i >= 0; i--)
                {
                    if (this._items[i].Classid == item.Classid && this._items[i] != item)
                    {
                        this._items.RemoveAt(i);
                    }
                }
                item.IsExpand = false;
            }
            else if (item.IsClass == true)
            {
                item.IsExpand = true;
                try
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(_xmlpath);
                    XmlNodeList Qd = doc.DocumentElement.ChildNodes[item.Classid].ChildNodes;
                    int i = 1;
                    foreach (XmlNode Qi in Qd)
                    {
                        this._items.Insert(
                        this.SelectedIndex + i,
                        new WxListBoxItem(
                        item.Classid,
                        int.Parse(Qi.Attributes["qq"].Value),
                        Qi.Attributes["title"].Value,
                        Qi.Attributes["remarks"].Value,
                        Qi.Attributes["text"].Value,
                        new Bitmap(Qi.Attributes["image"].Value),
                        true,
                        true,
                        true));
                        i++;

                    }

                }
                catch (Exception A)
                {
                    Console.WriteLine("Exception: {0}", A.ToString());
                }

            }
            this.Invalidate();
        }
        protected override void OnDoubleClick(EventArgs e)
        {
            base.OnDoubleClick(e);
            WxListBoxItem item = Items[this.SelectedIndex];
            // MessageBox.Show(this.SelectedIndex.ToString());
        }
        protected override void OnMouseMove(MouseEventArgs e)
        {
            base.OnMouseMove(e);
            for (int i = 0; i < Items.Count; i++)
            {
                Rectangle bounds = this.GetItemRectangle(i);
                if (bounds.Contains(e.X, e.Y))
                {
                    if (Items[i] != mouseitem)
                    {
                        mouseitem = Items[i];
                        this.Invalidate();
                    }
                }
            }
        }

        #region 拖动
        //private ListBox sourcelbl;
        protected override void OnDragOver(DragEventArgs e)
        {
            base.OnDragOver(e);
            //拖动源和放置的目的地一定是一个ListBox
            if (e.Data.GetDataPresent(typeof(System.String)))
            {
                e.Effect = DragDropEffects.Move;
            }
            else
                e.Effect = DragDropEffects.None;


        }
        protected override void OnDragDrop(DragEventArgs drgevent)
        {
            base.OnDragDrop(drgevent);
        }
        #endregion
        //计算文本长度
        private int StringLength(string text)
        {
            int len = 0;

            for (int i = 0; i < text.Length; i++)
            {
                byte[] byte_len = System.Text.Encoding.Default.GetBytes(text.Substring(i, 1));
                if (byte_len.Length > 1)
                    len += 2; //如果长度大于1，是中文，占两个字节，+2
                else
                    len += 1; //如果长度等于1，是英文，占一个字节，+1
            }

            return len;
        }
    }
}